using System.Data;
using System.IO;
using DataStubGenerator.Views;

namespace DataStubGenerator
{
    public class FileModel
    {
        private DataTable _table;
        private string _fileName;

        public DataTable Table
        {
            get { return _table; }
        }

        public string  FileName
        {
            get { return _fileName; }
        }

        public bool LoadFile(string fileName)
        {
            if (fileName != null) {
                _fileName = fileName;

                _table = new DataTable();
                Table.ReadXml(_fileName);

                return true;
            }else return false;
        }

        public void SaveFile(string name)
        {
            _fileName = name;

            using (StreamWriter myWriter = new StreamWriter(FileName))
                Table.WriteXml(myWriter, XmlWriteMode.WriteSchema);
        }

        public void CreateTableFromSql(string sqlText)
        {
            FileData data = new FileData();

            _table = data.GetTableBy(sqlText);
            _table.TableName = FindTableName(sqlText);
        }

        private string FindTableName(string sql)
        {
            int afterFromIndex = sql.ToLower().IndexOf("from") + "from ".Length;
            string[] wordsAfterFrom = sql.Substring(afterFromIndex).Split(' ','\n');
            return wordsAfterFrom[0];
        }
    }
}